package com.taptech.doufu.services.history;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.taptech.doufu.ui.activity.story.StoryDetailsActivity;
import com.taptech.doufu.util.NetworkUtil;
import com.taptech.doufu.R;
import com.taptech.doufu.ui.activity.CartoonScanNewActivity;
import com.taptech.doufu.ui.activity.NovelSectionDetailsActivity;
import com.taptech.doufu.ui.activity.weex.SimpleWeexActivity;
import com.taptech.doufu.ui.activity.base.DiaobaoBaseActivity;
import com.taptech.doufu.app.WeMediaApplication;
import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.event.BaseEventBusBean;
import com.taptech.doufu.event.EventBusConstant;
import com.taptech.doufu.util.UIUtil;
import com.taptech.doufu.util.sp.DiaoBaoSharedPreferences;
import com.taptech.doufu.ui.view.WaitDialog;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;
import java.util.List;

@SuppressLint("NewApi")
public class NovelHistoryView implements OnItemClickListener {
    private ListView mHistoryListView;
    public HistoryAdapter historyAdapter;
    private WaitDialog loadNoveDialog;
    private View no_content_ly;

    private Context mContext;

    public NovelHistoryView(Context mContext, View view) {
        this.mContext = mContext;
        loadNoveDialog = new WaitDialog(mContext, R.style.loadNovelDialog, "");
        no_content_ly =  view.findViewById(R.id.no_content_ly);
        mHistoryListView = (ListView) view.findViewById(R.id.novel_history_content);
        mHistoryListView.setOnItemClickListener(this);
        mHistoryListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                if (firstVisibleItem == 0) {
                    View firstVisibleItemView = mHistoryListView.getChildAt(0);
                    if (firstVisibleItemView != null && firstVisibleItemView.getTop() == 0) {
//                        Log.d("ListView", "##### 滚动到顶部 #####");
                    }
                } else if ((firstVisibleItem + visibleItemCount) == totalItemCount) {
                    View lastVisibleItemView = mHistoryListView.getChildAt(mHistoryListView.getChildCount() - 1);
                    if (lastVisibleItemView != null && lastVisibleItemView.getBottom() == mHistoryListView.getHeight()) {
//                        Log.d("ListView", "##### 滚动到底部 ######");
                        if (last > -1) {
                            loadHistoryRecord();
                        }
                    }
                }
            }
        });
        loadHistoryRecord();

    }


    private void showNoContentView() {
        if (historyAdapter != null && historyAdapter.list!=null && historyAdapter.list.size()>0) {
            no_content_ly.setVisibility(View.GONE);
        }else{
            no_content_ly.setVisibility(View.VISIBLE);

        }
    }

    private int last = 0;
    private int size = 30;

    public void loadHistoryRecord() {
        if (loadNoveDialog != null && !loadNoveDialog.isShowing()) {
            loadNoveDialog.show();
        }
        ReadHistoryUtil.getReadHistory(new ReadHistoryUtil.OnGetDataResult() {
            @Override
            public void onNext(List<ReadRecord> list) {
                if (list != null && list.size() > 0) {
                    if (historyAdapter != null) {
                        historyAdapter.addLists(list);
                    }else{
                        historyAdapter = new HistoryAdapter(list);
                        mHistoryListView.setAdapter(historyAdapter);
                    }
                    if (list.size() < size) {
                        last = -1;
                    }else{
                        last+=list.size();
                    }
                }else {
                    last = -1;
                }
                showNoContentView();
                if (loadNoveDialog != null && loadNoveDialog.isShowing()) {
                    loadNoveDialog.dismiss();
                }
            }

            @Override
            public void onError(Throwable e) {
                last = -1;
                if (loadNoveDialog != null && loadNoveDialog.isShowing()) {
                    loadNoveDialog.dismiss();
                }
                showNoContentView();
                if (!NetworkUtil.isNetworkUsable(mContext)) {
                    Toast.makeText(mContext, "网络异常，请检查你的网络", Toast.LENGTH_SHORT).show();
                }

            }
        },size,last);

    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        ReadRecord hisReadRecord = historyAdapter.getItem(position);
        if ((hisReadRecord != null)) {
            if (hisReadRecord.getType() == Constant.OBJECT_TYPE_CHATNOVEL) {
                HashMap map = new HashMap();
                map.put("id", hisReadRecord.getNovel_id());
                String type = DiaoBaoSharedPreferences.getSharedPreferencesValueToString("themeType",WeMediaApplication.applicationContext,"");
                if (!TextUtils.isEmpty(type)) {
                    map.put("themeType", JSON.parse(type));
                }
                SimpleWeexActivity.startActivity(mContext,"vue/speakNovel/read/WWRead.js", map);
            }else if(hisReadRecord.getType() == Constant.OBJECT_TYPE_CARTOON){
                //漫画
                Intent intent = new Intent(mContext, CartoonScanNewActivity.class);
                intent.putExtra(Constant.CARTOON_ID, hisReadRecord.getNovel_id());
                intent.putExtra(Constant.POSITION, position);
                mContext.startActivity(intent);
            }else{
                if (hisReadRecord.getSingle_page() > 0) {
                    StoryDetailsActivity.Companion.startActivity(mContext,hisReadRecord.getNovel_id());
                }else{
                    //小说
                    Intent intent = new Intent(mContext, NovelSectionDetailsActivity.class);
                    intent.putExtra(Constant.IS_SELF,true);
                    intent.putExtra(Constant.ARTICLE_ID, hisReadRecord.getSection_id());
                    intent.putExtra(Constant.ARTICLE_NOVELID, hisReadRecord.getNovel_id());
                    ((Activity) mContext).startActivityForResult(intent, 777);
                }
            }
        }

    }


    public class HistoryAdapter extends BaseAdapter {
        List<ReadRecord> list;
        public HistoryAdapter(List<ReadRecord> novelIdList)
        {
            list = novelIdList;
        }


        public void addLists(List<ReadRecord> list) {
            if (list != null && list.size() > 0) {
                if (this.list != null) {
                    this.list.addAll(list);
                }
                notifyDataSetChanged();
            }
        }


        @Override
        public int getCount()
        {
            return list.size();
        }

        @Override
        public ReadRecord getItem(int position) {
            if (list != null && list.size() > position) {
                return list.get(position);
            }
            return null;
        }

        public String getNovelId(int position) {
            return getItem(position)!=null?getItem(position).getNovel_id():"";
        }


        public int getType(int pos) {
            return getItem(pos)!=null?getItem(pos).getType():Constant.OBJECT_TYPE_NOVEL;
        }

        @Override
        public long getItemId(int position)
        {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ReadRecord model = getItem(position);
            if (model == null) {
                return new View(mContext);
            }
            ViewHolder viewHodler ;
            if (convertView == null) {
                viewHodler = new ViewHolder();
                convertView = LayoutInflater.from(mContext).inflate(R.layout.home_novel_history_list_item, null);
                viewHodler.title = (TextView) convertView.findViewById(R.id.home_novel_history_title);
                viewHodler.progress = (TextView) convertView.findViewById(R.id.home_novel_history_progress);
                viewHodler.ivOpe = (ImageView) convertView.findViewById(R.id.iv_novel_history);
                convertView.setTag(viewHodler);
            } else {
                viewHodler = (ViewHolder) convertView.getTag();
            }
            viewHodler.title.setText(model.getName());
            if (model.getType() == Constant.OBJECT_TYPE_CHATNOVEL) {
                viewHodler.progress.setText(model.getProgress());
            }else{
                viewHodler.progress.setText(list.get(position).getPosition() + " / " +
                        list.get(position).getAll_num());
            }
            viewHodler.ivOpe.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //弹出选择边框
                    showDialog(position);
                }
            });
            return convertView;
        }

        class ViewHolder {
            TextView title;
            TextView progress;
            ImageView ivOpe;
        }

    }

    private Button btDel, btCancel;
    private void showDialog(final int pos) {
        View view = ((DiaobaoBaseActivity) (mContext)).getLayoutInflater().inflate(R.layout.photo_choose_dialog, null);
        final Dialog dialog = new Dialog(mContext, R.style.transparentFrameWindowStyle);
        dialog.setContentView(view, new android.view.ViewGroup.LayoutParams(android.view.ViewGroup.LayoutParams.FILL_PARENT,
                android.view.ViewGroup.LayoutParams.WRAP_CONTENT));
        btDel = (Button) view.findViewById(R.id.btn_del);
        btDel.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                if((dialog!=null)&&(dialog.isShowing())) {
                    dialog.cancel();
                }
                if (loadNoveDialog != null && !loadNoveDialog.isShowing()) {
                    loadNoveDialog.show();
                }
                ReadHistoryUtil.deleteData((Activity) mContext,historyAdapter.getNovelId(pos), historyAdapter.getType(pos), new ReadHistoryUtil.OnPustDataResult() {
                    @Override
                    public void onNext() {
                        UIUtil.toastMessage(mContext, "删除成功");
                        historyAdapter.list.remove(pos);
                        //更新书架轮播图
                        BaseEventBusBean eventBus = new BaseEventBusBean();
                        eventBus.setTag(EventBusConstant.TAG_BOOK_SHELF);
                        EventBus.getDefault().post(eventBus);
                        if (historyAdapter.list.size() == 0) {
                            no_content_ly.setVisibility(View.VISIBLE);
                        }
                        historyAdapter.notifyDataSetChanged();
                        if (loadNoveDialog != null && loadNoveDialog.isShowing()) {
                            loadNoveDialog.dismiss();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        UIUtil.toastMessage(mContext, "删除失败");
                        if (loadNoveDialog != null && loadNoveDialog.isShowing()) {
                            loadNoveDialog.dismiss();
                        }

                    }
                });
            }
        });
        btCancel = (Button) view.findViewById(R.id.btn_cancel);
        btCancel.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                if ((dialog != null) && (dialog.isShowing()))
                {
                    dialog.cancel();
                }
            }
        });
        Window window = dialog.getWindow();
        // 设置显示动画
        window.setWindowAnimations(R.style.main_menu_animstyle);
        WindowManager.LayoutParams wl = window.getAttributes();
        wl.x = 0;
        wl.y = ((DiaobaoBaseActivity) (mContext)).getWindowManager().getDefaultDisplay().getHeight();
        // 以下这两句是为了保证按钮可以水平满屏
        wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
        wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;

        // 设置显示位置
        dialog.onWindowAttributesChanged(wl);
        // 设置点击外围解散
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();
    }

    /**
     *  对外提供删除全部的方法
     */
    public void deleteAll(){
        if (loadNoveDialog != null && !loadNoveDialog.isShowing()) {
            loadNoveDialog.show();
        }
        ReadHistoryUtil.deleteAllData((Activity) mContext,new ReadHistoryUtil.OnPustDataResult() {
            @Override
            public void onNext() {

                //更新书架轮播图
                BaseEventBusBean eventBus = new BaseEventBusBean();
                eventBus.setTag(EventBusConstant.TAG_BOOK_SHELF);
                EventBus.getDefault().post(eventBus);
                UIUtil.toastMessage(mContext, "删除成功");
                historyAdapter.list.clear();
                no_content_ly.setVisibility(View.VISIBLE);
                historyAdapter.notifyDataSetChanged();
                if (loadNoveDialog != null && loadNoveDialog.isShowing()) {
                    loadNoveDialog.dismiss();
                }
            }

            @Override
            public void onError(Throwable e) {
                UIUtil.toastMessage(mContext, "删除失败");
                if (loadNoveDialog != null && loadNoveDialog.isShowing()) {
                    loadNoveDialog.dismiss();
                }
            }
        });
    }
}
